package com.wisdom.benefit.jufa.my;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseApplication;
import com.wisdom.benefit.jufa.base.BaseNewFragment;
import com.wisdom.benefit.jufa.main.HomeFragment;
import com.wisdom.benefit.jufa.main.LoginActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.product.CollectionAccountActivity;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.widget.CircleImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import androidx.annotation.Nullable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MineFragment extends BaseNewFragment implements View.OnClickListener {
    public static final String TAG = HomeFragment.class.getSimpleName();
    private TextView versionTv;
    private RelativeLayout caRl, setRl, logoutRl;
    private Dialog dialog;
    private View inflate;
    private TextView camera;
    private TextView pic;
    private TextView cancel;
    private TextView nameTv;
    private CircleImageView iv;
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private static final int PHOTO_CLIP = 3;
    private SoundPool soundPool;
    private int soundID;

    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initSound();

    }

    @Override
    public int setLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public void findViewById(View view) {
        //基本信息
        caRl = view.findViewById(R.id.mine_collect_account_rl);
        //安全设置
        setRl = view.findViewById(R.id.mine_collect_setting_rl);
        //切换头像
        iv = view.findViewById(R.id.mine_pic_iv);
        //姓名
        nameTv = view.findViewById(R.id.mine_name_tv);
        //退出
        logoutRl = view.findViewById(R.id.mine_logout_rl);
    }

    @Override
    public void setViewData(View view) {

    }


    @Override
    public void setClickEvent(View view) {
        //当前收款账户
        caRl.setOnClickListener(this);
        //安全设置
        setRl.setOnClickListener(this);
        //切换头像
        iv.setOnClickListener(this);
        //退出
        logoutRl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mine_collect_account_rl:
                Intent intent = new Intent(getActivity(), CollectionAccountActivity.class);
                startActivity(intent);
                break;
            case R.id.mine_collect_setting_rl:
                Intent setIntent = new Intent(getActivity(), SettingActivity.class);
                startActivity(setIntent);
                break;
            case R.id.mine_pic_iv:

                break;
            case R.id.camera:
                getCamera();
                dialog.dismiss();
                break;
            case R.id.pic:
                getPhoto();
                dialog.dismiss();
                break;
            case R.id.cancel:
                dialog.dismiss();
                break;
            case R.id.mine_logout_rl:
                logout(BaseApplication.getContext().getUserId());
                break;

        }
    }

    public void show(View view) {
        dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.photo_dialog_item, null);
        //初始化控件
        camera = (TextView) inflate.findViewById(R.id.camera);
        pic = (TextView) inflate.findViewById(R.id.pic);
        cancel = (TextView) inflate.findViewById(R.id.cancel);
        camera.setOnClickListener(this);
        pic.setOnClickListener(this);
        cancel.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    /**
     * 从相册选择图片来源
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    /**
     * 从系统相机选择图片来源
     */
    private void getCamera() {
//        //创建拍照存储的图片文件
//        tempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/image/", System.currentTimeMillis() + ".jpg");
//
//        //跳转到调用系统相机
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        //这里区分下android版本再进行不同的操作
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            //设置7.0中共享文件，分享路径定义在xml/provider_pathsaths.xml
//            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            //BuildConfig.APPLICATION_ID + ".fileProvider"
//            //这个参数就是之前说到的android:authorities标识了
//            Uri contentUri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
//        } else {
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
//        }
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                switch (resultCode) {
                    case -1://-1表示拍照成功
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data");
                        String a = bitmapToBase64(bitmap);
                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        iv.setImageBitmap(decodedByte);
                        break;
                }
                break;

            case PHOTO_REQUEST://从相册取
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                        String a = bitmapToBase64(bitmap);
                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        iv.setImageBitmap(decodedByte);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //对相册取出照片进行裁剪

                }
                break;
//            case PHOTO_CLIP:
//                //完成
//                if (data != null) {
//                    setPicToView(data);
////                    Bundle extras = data.getExtras();
////                    if (extras != null) {
////                        Bitmap photo = extras.getParcelable("data");
////                        try {
////                            //获得图片路径
////                            File filepath = saveFile(photo, Environment.getExternalStorageDirectory().toString(), "hand.jpg");
////                            //上传照片
////
////                        } catch (IOException e) {
////                            e.printStackTrace();
////                        }
////                        //上传完成将照片写入imageview与用户进行交互
//////                        mImageView.setImageBitmap(photo);
////                    }
//                }
//                break;
        }
    }


    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            userInfo(BaseApplication.getContext().getUserId());

        } else {
            //相当于Fragment的onPause，为false时，Fragment不可见
        }
    }

    /**
     * 个人信息
     */
    private void userInfo(String userId) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .personalInformation(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        //姓名
                        nameTv.setText(response.getData().getUserName());
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("获取数据失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 推出登陆
     */
    private void logout(String userId) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .logout(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        //步骤1：创建一个SharedPreferences对象
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                        //步骤2： 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件
                        editor.putString("isHaveLogin", "0");
                        //步骤4：提交
                        editor.commit();
                        BaseApplication.getContext().setDeviceId("");
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("退出失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    @SuppressLint("NewApi")
    private void initSound() {
        soundPool = new SoundPool.Builder().build();
        soundID = soundPool.load(getActivity(), R.raw.mysound, 1);
    }


    private void playSound() {
        soundPool.play(
                soundID,
                0.1f,      //左耳道音量【0~1】
                0.5f,      //右耳道音量【0~1】
                0,         //播放优先级【0表示最低优先级】
                0,         //循环模式【0表示循环一次，-1表示一直循环，其他表示数字+1表示当前数字对应的循环次数】
                1          //播放速度【1是正常，范围从0~2】
        );
    }

}
